# -*- coding: utf-8 -*-
import os
import re

def remove_title_from_chapter(file_path):
    with open(file_path, 'r') as f:
        content = f.read().decode('utf-8')
    
    # 移除开头的空行和标题行（标题行通常是"第X章：xxx"或"第X章 xxx"的格式）
    lines = content.split('\n')
    non_empty_lines = [line for line in lines if line.strip()]
    
    # 检查第一行是否为标题行
    if non_empty_lines and re.match(ur'^第[一二三四五六七八九十百千]+章[：\s].*', non_empty_lines[0]):
        content = '\n'.join(non_empty_lines[1:])
    
    # 写回文件
    with open(file_path, 'w') as f:
        f.write(content.encode('utf-8'))

def process_all_chapters(chapters_dir):
    for filename in os.listdir(chapters_dir):
        if filename.startswith('chapter') and filename.endswith('.txt'):
            file_path = os.path.join(chapters_dir, filename)
            remove_title_from_chapter(file_path)
            print('Processed ' + filename)

# 处理chapters目录下的所有章节文件
chapters_dir = 'd:/studyNew/windsurf/test1/chapters'
process_all_chapters(chapters_dir)
